package com.strategy.demo.factory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import com.strategy.demo.INoticeStrategy;
import com.strategy.demo.annotation.NoticeType;
import com.strategy.demo.enums.NoticeTypeEnum;

/**
 * 通知策略工厂 （实现类中有事务版）
 * @author francis
 */
@Component
public class NoticeStrategyFactory2 implements BeanPostProcessor{

	private Map<NoticeTypeEnum, INoticeStrategy> strategyMap = new ConcurrentHashMap<>();
	
	/**
	 * 事务代理会影响bean获取其bean上的注解，此处用BeanPostProcessor 在事务代理之前 拿到bean 的注解
	 */
	@Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
		if(bean instanceof INoticeStrategy) {
			Class<? extends Object> clazz = bean.getClass();
			NoticeType annotation = clazz.getAnnotation(NoticeType.class);
			this.strategyMap.put(annotation.value(), (INoticeStrategy)bean);
		}
		return bean;
	}
	
	/**
	 * 寻找对应得策略处理器
	 */
	public INoticeStrategy getHandler(NoticeTypeEnum type) {
		return strategyMap.get(type);
	}
	
}
